/***********************************************************
 * Mapping management including lunGroup
 ***********************************************************/

/**
 * lunGroup manage
 */
var Group = {
	/**
	 * Show group list
	 */
	list : function() {
		// Request user list url.
		var groupListUrl = baseURL + "/mapping/lg/list"
		$.ajax({
			type : "get",
			url : groupListUrl,
			dataType : "html",
			success : function(html) {
				// Request successfully and fill the data.
				$("#lgList").empty().html(html);
			}
		});
	},
	/**
	 * New group
	 */
	create : function() {
		var title = localeMsg.lunGroup.create;
		_groupId = "";
		common.dialog({
			obj : "#editGroupDialog",
			type : "get",
			url : baseURL + "/mapping/lg/edit",
			title : title,
			width : 400,
			confirm : function() {
				if($("#editGroupForm").form('validate')!=true){
					return;
				}
				Group.save();
			}
		});
	},
	/**
	 * Edit group
	 */
	edit : function() {
		// Get the first groupId from checked buttons.
		var groupIds =[];
		$("input[name='groupId']:checked").each(function(){
			groupIds.push($(this).val()); 
            });
		// The title of edit dialog
		var title = localeMsg.lunGroup.create;
		var param = {};
		if(groupIds.length==0){
			common.showTip({
				title : localeMsg.common.warn ,
				text : localeMsg.common.selectMsg
			});
		}else if(groupIds.length>1){
			common.showTip({
				title : localeMsg.common.warn ,
				text : localeMsg.common.selectMsg
			});
		}else{
			var groupId = $("input[name='groupId']:checked").eq(0).val();
			_groupId = groupId;
			title = localeMsg.lunGroup.edit;
			param.groupId = groupId;
			common.dialog({
				obj : "#editGroupDialog",
				type : "get",
				url : baseURL + "/mapping/lg/edit",
				param : param,
				title : title,
				width : 400,
				confirm : function() {
					if($("#editGroupForm").form('validate')!=true){
						return;
					}
					Group.save();
				}
			});
		}
	},
	/**
	 * 分配权重
	 */
	weigh : function() {
		// Get the first groupId from checked buttons.
		var groupIds =[];
		$("input[name='name']:checked").each(function(){
			groupIds.push($(this).val()); 
            });
		// The title of edit dialog
		var title = localeMsg.lunGroup.create;
		var param = {};
		if(groupIds.length==0){
			common.showTip({
				title : localeMsg.common.warn ,
				text : localeMsg.common.selectMsg
			});
		}else if(groupIds.length>1){
			common.showTip({
				title : localeMsg.common.warn ,
				text : localeMsg.common.selectMsg
			});
		}else{
			var id = $("#id").val();
			var groupId = $("input[name='name']:checked").eq(0).val();
			//_groupId = groupId;
			title = localeMsg.qos.weight;
			param.groupId = groupId;
			common.dialog({
				obj : "#editGroupDialog",
				type : "get",
				url : baseURL + "/mapping/lg/showWeigh",
				param : param,
				title : title,
				width : 400,
				confirm : function() {
					/*if($("#editGroupForm").form('validate')!=true){
						return;
					}*/
					Group.saveWeigh(id);
				}
			});
		}
	},
	
	/**
	 * Save group
	 */
	save : function() {
		var groupId = $("#editGroupForm input[id='id']").eq(0).val();
		var groupName = $("#editGroupForm input[id='groupName']").eq(0).val();
		var saveUrl = baseURL + "/mapping/lg/save";
		$.ajax({
			type : "post",
			url : saveUrl,
			data : {groupId : groupId , groupName : groupName},
			dataType : "json",
			success : function(json) {
				// Request successfully and fill the data.
				if (json.result && json.result == "success") {
					common.showTip({
						title : localeMsg.common.prompt,
						text : localeMsg.common.saveSuccess,
						success : true,
						callback : function() {
							Group.list();
						}
					});
				} else {
					common.showTip({title : localeMsg.common.warn, text : localeMsg.common.saveFailed});
				}
			}
		})
	},
	
	/**
	 * saveWeigh
	 */
	saveWeigh : function(groupId) {
		var lunId = $("#editGroupForm input[id='id']").eq(0).val();
		//var weighVal = $("#editGroupForm input[id='groupName']").eq(0).val();
		var weighVal = $("#editGroupForm select[id='groupName']").eq(0).val();
		var saveUrl = baseURL + "/mapping/lg/saveWeigh";
		$.ajax({
			type : "post",
			url : saveUrl,
			data : {id : lunId , weighVal : weighVal,groupId:groupId},
			dataType : "json",
			success : function(json) {
				// Request successfully and fill the data.
				if (json.result && json.result == "success") {
					common.showTip({
						title : localeMsg.common.warn,
						text : localeMsg.common.saveSuccess,
						success : true,
						callback : function() {
							//Group.showLunsRefresh(groupId);
							//Group.showLunslist(groupId);
							//alert(json.data);
							location.reload();
							//history.go(-1);
							//alert($("#selectId").val());
							//$("#selectId").val(json.data);
						}
					});
				} else {
					common.showTip({title : localeMsg.common.warn, text : localeMsg.common.saveFailed});
				}
			}
		})
	},
	
	
	
	/**
	 * Remove groups confirm
	 */
	remove : function(){
		var roleId=[];
		$('input[name="groupId"]:checked').each(function(){
			roleId.push($(this).val()); 
            });  
		if (Object.keys(roleId).length === 0){
			common.showTip({
				title : localeMsg.common.warn,
				text : localeMsg.common.selectMsg
			});
		}else{
			var confirmMessage = localeMsg.common.relateddeleteconfirm
				common.confirmDialog(confirmMessage,Group.removeDel);
		}

	},
	
	qosByNameAndPoolName :function(){
		var qosTypeValue = $('#box').combobox('getValue');
		$("#qosForm").ajaxSubmit({
			success : function(json) {
//				alert(json.result);
				if (json.result && json.result == "success") {
					common.showTip({
						title : localeMsg.common.prompt,
						text : "保存成功!",
						success: true,
						callback : function() {
							Group.list();
						}
					});
				} else {
					common.showTip({
						title : localeMsg.common.warn,
						text : localeMsg.common.saveFailed,
						success: false
					});
				}
			},
		});
	},
	/**
	 * qos
	 */
	qos : function() {
		
		var groupIds =[];
		$("input[name='groupId']:checked").each(function(){
			groupIds.push($(this).val()); 
            });
		// The title of edit dialog
		var title = "QoS";
		var param = {};
		if(groupIds.length==0){
			common.showTip({
				title : localeMsg.common.warn ,
				text : localeMsg.common.selectMsg
			});
		}else if(groupIds.length>1){
			common.showTip({
				title : localeMsg.common.warn ,
				text : localeMsg.common.selectMsg
			});
		}else{
			var targetId = $("input[name='groupId']:checked").val();
			param.targetId = targetId;
			common.dialog({
				obj : "#editGroupDialog",
				type : "get",
				url : baseURL + "/mapping/lg/qosByGroup",
				param : param,
				title : title,
				width : 400,
				confirm : function() {
					if($("#qosForm").form('validate')!=true){
						return;
					}
					Group.qosByNameAndPoolName();
				}
			});
		}
		
		
		
		
		/*var targetId = $("input[name='groupId']:checked").eq(0).val();
		var title = "QoS";
		var param = {};
		if (targetId && targetId != "") {
			title = "QoS";
			param.targetId = targetId;
			common.dialog({
				obj : "#editGroupDialog",
				type : "get",
				url : baseURL + "/mapping/lg/qosByGroup",
				param : param,
				title : title,
				width : 400,
				confirm : function() {
					if($("#qosForm").form('validate')!=true){
						return;
					}
					Group.qosByNameAndPoolName();
				}
			});
		}else{
			common.showTip({
				title : "Warn",
				text : "您还未选择任何数据!"
			});
		}*/
	},
	/**
	 * Remove groups
	 */
	removeDel : function() {
		//  Remove  records
		var groupId=[];
		$('input[name="groupId"]:checked').each(function(){
			groupId.push($(this).val()); 
        });  
		
		$.ajax({
			type : "post",
			url : baseURL + "/mapping/lg/remove",
			data : {groupIds : groupId},
			traditional: true,
			dataType : "json",
			success : function(json) {
				if (json.result && json.result == "success") {
					common.showTip({
						title : localeMsg.common.prompt,
						text : localeMsg.common.deleteSuccess,
						success : true,
						callback : function() {
							Group.list();
						}
					});
				} else {
					common.showTip({title : localeMsg.common.warn, text : localeMsg.common.deleteFailed});
				}
			}
		});
	},
	
	validate : function(){
	    $('#groupName').validatebox({
	        required: true,
	        validType : ['vername','uniquename["/mapping/lg/validateName","'+_groupId+'"]']
	    });
	},
	
	/**
	 * 显示target选项
	 * @param e
	 */
	showTargets : function(element) {
		$.ajax({
			type : "get",
			url : baseURL + "/mapping/target/list.json",
			dataType : "json",
			success : function(json) {
				for (var k in json) {
					$(element).append('<option value="' + json[k].id + '">' + json[k].name + '</option>');
				}
			}
		});
	},
	
	/**
	 * 显示lun列表
	 * @param element
	 * @param type 显示类型
	 */
	showLuns : function(element, type) {
		var groupId = $(element).parent().siblings().find("input[name='groupId']").val();
		var title = localeMsg.lun.list;
		var url = baseURL + "/cluster/lun/listByGroup";
		var param = {groupId : groupId};
		var confirmText = localeMsg.common.deleted;
		if (type) {
			param.type = type;
			title = localeMsg.lun.add;
			confirmText = localeMsg.common.confirm;
		}
		var dialog;
		if ($("#lunList").length < 1) {
			$("#listLunForm").append('<div id="lunList" ></div>');
			dialog = "#lunList";
		}
		common.dialog({
			obj : dialog,
			type : "get",
			url : url,
			param : param,
			title : title,
			width : 600,
			confirm : function(dialog) {
				var lunIdArr = [];
				var lunSelectValArr = [];
				$(dialog).find("input[name='name']:checked").each(function() {
					lunIdArr.push($(this).val());
					
				});
				if (type) {
					confirmText = localeMsg.common.confirm;
					$(dialog).find("select[name='select']").each(function() {
						if($(this).parent().siblings().find("input[name='name']:checked").val()!=undefined){
							lunSelectValArr.push($(this).val());
						}
						
					});
				};
				Group.saveGroupLuns(groupId, lunIdArr,type,lunSelectValArr);
			},
			confirmText : confirmText,
			onOpen : function() {
				$("#listLunForm").ajaxpager({
					target: "#lunList",
					callback: function() {
						Group.showLunsByPager(groupId, type);
					}
				});
			}
		});
	},
	/**
	 * 
	 * @param groupId
	 * @param type
	 */
	showLunsByPager : function(groupId, type) {
		var pageNumber = $("#lunList input[name='pageNumber']").val();
		var url = baseURL + "/cluster/lun/listByGroup";
		var param = {groupId : groupId, pageNumber : pageNumber};
		if (type) {
			param.type = type;
		}
		$.ajax({
			type : "get",
			url : url,
			data : param,
			success : function(html) {
				$("#lunList").empty().html(html);
				$("#lunList").dialog("resize");
			}
		});
	},
	
	showLunslist : function(element) {
		var title = localeMsg.lun.list;
		var url = baseURL + "/cluster/lun/listByGroup";
		var param = {groupId : element};
		$.ajax({
			type : "get",
			url : groupListUrl,
			data :{groupId : element},
			dataType : "html",
			success : function(html) {
				// Request successfully and fill the data.
				$("#weighList").empty().html(html);
			}
		});
		
	},
	
	
	/**
	 * 保存group-lun关系
	 * @param groupId
	 * @param lunIdArr
	 */
	saveGroupLuns : function(groupId, lunIdArr,type,lunSelectValArr) {
		
		if(lunIdArr.length>0){
		$.ajax({
			type : "post",
			url : baseURL + "/mapping/lg/luns",
			traditional: true,
			data : {groupId: groupId, lunIds : lunIdArr, type : type,lunSelectVals : lunSelectValArr},
			dataType : "json",
			success : function(json) {
				common.showTip({
					title : localeMsg.common.prompt,
					text : localeMsg.common.saveSuccess,
					success : true
				});
			}
		});
	    }
	},
	/**
	 * 显示未与指定lungroup做映射的lun列表
	 * @param element
	 */
	/*showLuns : function(element) {
		var groupId = $("#lgList input[name='groupId']:checked").val();
		var url = baseURL + "/mapping/luns";
		var param = {groupId : groupId};
		if(groupId == undefined){
			common.showTip({
				title : "Info",
				text : "请先选中一项!"
			});
		}else{
			common.dialog({
				type : "get",
				url : url,
				param : param,
				title : "Lun List",
				width : 600,
				confirm : function(dialog) {
					var lunArr = [];
					$(dialog).find("input[name='lunId']:checked").each(function() {
						lunArr.push($(this).val());
					});
					Group.mapping(groupId, lunArr);
				}
			});
		}
	},*/
	/**
	 * 查看映射信息
	 * @param element
	 */
	showMappings : function() {
		
		var groupId = $("#lgList input[name='groupId']:checked").val();
		var url = baseURL + "/mapping/list";
		var param = {groupId : groupId};
		if(groupId == undefined){
			common.showTip({
				title : localeMsg.common.warn,
				text : localeMsg.common.selectMsg
			});
		}else{
			common.dialog({
				type : "get",
				url : url,
				param : param,
				title : localeMsg.lun.mapping,
				width : 600,
				confirm : function(dialog) {
					var lunArr = [];
					$(dialog).find("input[name='lunId']:checked").each(function() {
						lunArr.push($(this).val());
					});
					Group.unmapping(groupId, lunArr);
				}
			});
		}
	},
	/**
	 * 映射lunGroup-lun
	 * @param groupId
	 * @param lunArr
	 */
	mapping : function(groupId, lunArr) {
		$.ajax({
			type : "post",
			url : baseURL + "/mapping",
			traditional: true,
			data : {groupId: groupId, lunIds : lunArr},
			dataType : "json",
			success : function(json) {
				common.showTip({
					title : localeMsg.common.prompt,
					text : localeMsg.common.saveSuccess,
					success : true
				});
			}
		});
	},
	/**
	 * 解除映射
	 * @param groupId
	 * @param lunArr
	 */
	unmapping : function(groupId, lunArr) {
		$.ajax({
			type : "post",
			url : baseURL + "/mapping/delete",
			traditional: true,
			data : {groupId: groupId, ids : lunArr},
			dataType : "json",
			success : function(json) {
				common.showTip({
					title : localeMsg.common.prompt,
					text : localeMsg.common.saveSuccess,
					success : true
				});
			}
		});
	},
	
	creator :function(){
		var creatorIds=[];
		$('td[name="creator"]').each(function(){
			var id = $(this).attr("id");
			creatorIds.push(id); 
        });
		$.ajax({
			type : "get",
			url : baseURL + "/mapping/lg/creator",
			traditional: true,
			data :{creatorIds : creatorIds},
			dataType : "json",
			success : function(json){
				$('td[name="creator"]').each(function(){
					$(this).text(json[$(this).attr("id")]);
				})
			}
		});
	}
}

/**
 * 
 */
var lun = {
	/**
	 * Show lun list
	 */
	list : function() {
		// Request lun list url.
		var lunListUrl = baseURL + "/cluster/lun/list"
		$.ajax({
			type : "get",
			url : lunListUrl,
			dataType : "html",
			success : function(html) {
				$("#lunList").empty().html(html);
			}
		});
	},
	
    init :function(){
		
		$('#box').combobox({
			data : [
			        {"qosTypeId":0,
				      "qosType":"iops",
			        },
			        {"qosTypeId":1,
			      	"qosType":"带宽",} 
			        ],
			valueField : 'qosTypeId',
			textField : 'qosType',
			onSelect : function(record) {
				lun.change(record);
			},
		  onLoadSuccess: function () { //加载完成后,设置默认值
             /*var val = $(this).combobox("getData");
             for (var item in val[0]) {
                 if (item == "id") {
                     $(this).combobox("select", val[0][item]);
                 }
             }*/
			var qosType = $("#qosType").val();
			var val = $(this).combobox("getData");
			if(qosType==0){
				$('#box').combobox('setValue',val[0].qosTypeId);
			}else{
				$('#box').combobox('setValue',val[1].qosTypeId);
			}
         }
			
		});
		
	},

	change : function(record){
     var value = record.qosTypeId;
		if(value==0){
			$("#contentQos").empty().append("<input id='iopsId' type='hidden' name='qosType' value='"+value+"'/><table id='iopsTable'><tr><th style='width: 35%;' scope='row'>"+localeMsg.lun.ReadIops+"<span class='color_red'>*</span></th><td style='width: 85%;'>&nbsp;<input id='qosRead' type='text' name='qosRead' value=''/></td></tr><tr><th style='width: 35%;' scope='row'>"+localeMsg.lun.WriteIops+"<span class='color_red'>*</span></th><td style='width: 85%;'>&nbsp;<input id='qosWrite' type='text' name='qosWrite' value=''/></td></tr></table>");
		}else{
			$("#contentQos").empty().append("<input id='bandwidthId' type='hidden' name='qosType' value='"+value+"'/><table id='bandwidthTable'><tr><th style='width: 35%;' scope='row'>"+localeMsg.lun.readQos+"<span class='color_red'>*</span></th><td style='width: 85%;'>&nbsp;<input id='qosRead' type='text' name='qosRead' value=''/></td></tr><tr><th style='width: 35%;' scope='row'>"+localeMsg.lun.writeQos+"<span class='color_red'>*</span></th><td style='width: 85%;'>&nbsp;<input id='qosWrite' type='text' name='qosWrite' value=''/></td></tr></table>");
		}
		var qosType = $("#qosType").val();
		var qosReadValue=$("#qosReadHidden").val();
		var qosWriteValue=$("#qosWriteHidden").val();
		if(value==qosType){
			$("#qosRead").val(qosReadValue);
			$("#qosWrite").val(qosReadValue);
		}
		if(value==0){
			lun.validateIops(); 
		}else{
			lun.validateBandWidth(); 
		}
	},
	validateIops : function(){
		$('#qosRead,#qosWrite').validatebox({
			required : true,
			// 在页面取所有的qosRead,qosWrite与传进来的qosRead,qosWrite值比较,先验证正整数，让后验证大小
			validType :  ['positive_integer','iopsLength']     
		});
	},
	validateBandWidth : function(){
		$('#qosRead,#qosWrite').validatebox({
			required : true,
			// 在页面取所有的qosRead与传进来的qosRead值比较,先验证正整数，让后验证大小
			validType :  ['positive_integer','bandwidthLength'] 
		});
	},
	/**
	 * New lun
	 */
	create : function() {
		var title = localeMsg.lun.create;
		common.dialog({
			obj : "#editLunDialog",
			type : "get",
			url : baseURL + "/cluster/lun/edit",
			/*param : param,*/
			title : title,
			width : 400,
			confirm : function() {
				if($("#editLunForm").form('validate')!=true){
					return;
				}
				Lun.save();
			}
		});
	},
	/**
	 *Edit lun
	 */
	edit : function() {
		var lunIds =[];
		$("input[name='lunId']:checked").each(function(){
			lunIds.push($(this).val()); 
            });
		if(lunIds.length==0){
			common.showTip({
				title : localeMsg.common.warn ,
				text : localeMsg.common.selectMsg
			});
		}else if(lunIds.length>1){
			common.showTip({
				title : localeMsg.common.warn ,
				text : localeMsg.common.selectMsg
			});
		}else{
			var lunId = $("input[name='lunId']:checked").eq(0).val();
			title = localeMsg.lun.edit;
			param.lunId = lunId;
			common.dialog({
				obj : "#editLunDialog",
				type : "get",
				url : baseURL + "/cluster/lun/edit",
				param : param,
				title : title,
				width : 400,
				confirm : function() {
					if($("#editLunForm").form('validate')!=true){
						return;
					}
					Lun.save();
				}
			});
		}
		if (lunId && lunId != "") {
			
		}else{
			common.showTip({
				title : localeMsg.common.warn,
				text : localeMsg.common.selectMsg
			});
		}
	},
	/**
	 * Save lun
	 */
	save : function() {
		$("#editLunForm").ajaxSubmit({
			success : function(json) {
				if (json.result && json.result == "success") {
					common.showTip({
						title : localeMsg.common.prompt,
						text : localeMsg.common.saveSuccess,
						success : true,
						callback : function() {
							Lun.list();
						}
					});
				} else {
					common.showTip({title : localeMsg.common.warn, text : localeMsg.common.saveFailed});
				}
			}
		});
	},
	
	
	
	remove : function(){
		var lunId=[];
		$('input[name="lunId"]:checked').each(function(){
			lunId.push($(this).val()); 
            });  
		if (Object.keys(lunId).length === 0){
			common.showTip({
				title : localeMsg.common.warn,
				text : localeMsg.common.selectMsg
			});
		}else{
			var confirmMessage = localeMsg.common.relateddeleteconfirm
				common.confirmDialog(confirmMessage,Lun.removeDel);
		}

	},
	/**
	 * Remove luns
	 */
	removeDel : function() {
	
			var lunIds=[];
			$('input[name="lunId"]:checked').each(function(){
				lunIds.push($(this).val()); 
			});  
			
			$.ajax({
				type : "post",
				url : baseURL + "/cluster/lun/remove",
				data : {lunIds : lunIds},
				traditional: true,
				dataType : "json",
				success : function(json) {
					if (json.result && json.result == "success") {
						common.showTip({
							title : localeMsg.common.prompt,
							text : localeMsg.common.deleteSuccess,
							success : true,
							callback : function() {
								Lun.list();
							}
						});
					} else {
						common.showTip({title : localeMsg.common.warn, text : localeMsg.common.deleteFailed});
					}
				}
			});
		
	},
	validate : function(){
		$('#lunName').validatebox({
			required : true,
			validType :	'name'
		});
		$('#ipAddress').validatebox({
			required : true,
			validType : 'ip'
		});
	},
	
	creator :function(){
		var creatorIds=[];
		$('td[name="creator"]').each(function(){
			var id = $(this).attr("id");
			creatorIds.push(id); 
        });
		$.ajax({
			type : "get",
			url : baseURL + "/cluster/lun/creator",
			traditional: true,
			data :{creatorIds : creatorIds},
			dataType : "json",
			success : function(json){
				$('td[name="creator"]').each(function(){
					$(this).text(json[$(this).attr("id")]);
				})
			}
		});
	}
};